package org.trinity.netdisk.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.KeyExpirationEventMessageListener;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.stereotype.Component;

import java.util.Objects;

@Component
public class RedisMessageListener extends KeyExpirationEventMessageListener {

    private static Logger logger = LoggerFactory.getLogger(RedisMessageListener.class);

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    IFileService fileService;

    public RedisMessageListener(RedisMessageListenerContainer listenerContainer) { super(listenerContainer); }

    @Override
    public void onMessage(Message message, byte[] pattern) {
        String redisKey = (String) redisTemplate.getValueSerializer().deserialize(message.getBody());
        logger.info("回收站过期文件id：{}", redisKey);
        fileService.deleteFileFromRecycleBinByUserFileId(Long.parseLong(Objects.requireNonNull(redisKey)));
    }
}